library(readxl)
library(officer)
library(gtsummary)
library(flextable)

data_test = read.xlsx("./input/data918.xlsx", 3)
data_anal = data_test[, c(1, 9:13, 14:25, 27, 29:39)]
varsx = colnames(data_test)[c(14:25, 27)]  # 自变量
varsy = colnames(data_test)[c(9:13)]       # 因变量
varsc = colnames(data_test)[c(29:39)]      # 协变量

data_anal$id = as.character(data_anal$id)
data_anal[varsy] = lapply(data_anal[varsy], as.numeric)
data_anal[varsx] = lapply(data_anal[varsx], as.factor)
data_anal[varsc] = lapply(data_anal[varsc], as.factor)
 
x_data = data_anal[, c("id", varsx)]
x_data = unique((x_data))
x_summary = tbl_summary(x_data[, -1])
x_table = as_flex_table(x_summary)

c_data = data_anal[, c("id", varsc)]
c_data = unique((c_data))
c_summary = tbl_summary(c_data[, -1])
c_table = as_flex_table(c_summary)


sect_properties = prop_section(
  page_size = page_size(orient = "landscape",
                        width = 8.3, height = 11.7),
  type = "continuous",
  page_margins = page_mar()
)
save_as_docx(`x_table` = x_table, `c_table` = c_table, path = "./output/920_summary.docx", pr_section = sect_properties)